import BasePlugin from './BasePlugin';

/**
 * 历史记录插件 - 处理撤销/重做操作
 */
export default class HistoryPlugin extends BasePlugin {
    constructor() {
        super();
        this.history = {
            stack: [],
            position: -1,
            maxSteps: 30
        };
        this.isRecording = true;
        this.debounceTimeout = null;
        this.debounceDelay = 500;
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._setupEventListeners();
        this._recordInitialState();
    }

    /**
     * 撤销操作
     */
    undo() {
        if (!this.isEnabled() || !this.canvas) return;
        if (this.history.position <= 0) return;

        this.isRecording = false;
        this.history.position--;
        this._restoreState();
        this.isRecording = true;

        this.editor.emit('history:changed', {
            canUndo: this.canUndo(),
            canRedo: this.canRedo()
        });
    }

    /**
     * 重做操作
     */
    redo() {
        if (!this.isEnabled() || !this.canvas) return;
        if (this.history.position >= this.history.stack.length - 1) return;

        this.isRecording = false;
        this.history.position++;
        this._restoreState();
        this.isRecording = true;

        this.editor.emit('history:changed', {
            canUndo: this.canUndo(),
            canRedo: this.canRedo()
        });
    }

    /**
     * 清除历史记录
     */
    clear() {
        this.history = {
            stack: [],
            position: -1,
            maxSteps: this.history.maxSteps
        };
        this._recordInitialState();
    }

    /**
     * 检查是否可以撤销
     */
    canUndo() {
        return this.history.position > 0;
    }

    /**
     * 检查是否可以重做
     */
    canRedo() {
        return this.history.position < this.history.stack.length - 1;
    }

    /**
     * 设置最大历史步数
     */
    setMaxSteps(steps) {
        this.history.maxSteps = steps;

        // 如果当前历史记录超过新的最大步数，则裁剪
        if (this.history.stack.length > steps) {
            const excess = this.history.stack.length - steps;
            this.history.stack = this.history.stack.slice(excess);
            this.history.position = Math.max(0, this.history.position - excess);
        }
    }

    /**
     * 记录初始状态
     */
    _recordInitialState() {
        if (!this.canvas) return;

        const state = this.canvas.toJSON(['id', 'name', 'customType']);
        this.history.stack = [state];
        this.history.position = 0;

        this.editor.emit('history:changed', {
            canUndo: this.canUndo(),
            canRedo: this.canRedo()
        });
    }

    /**
     * 记录状态
     */
    _recordState() {
        if (!this.canvas || !this.isRecording) return;

        // 清除延迟记录定时器
        if (this.debounceTimeout) {
            clearTimeout(this.debounceTimeout);
        }

        // 延迟记录状态，避免频繁记录
        this.debounceTimeout = setTimeout(() => {
            const state = this.canvas.toJSON(['id', 'name', 'customType']);

            // 如果在历史记录中间位置进行了新操作，清除之后的记录
            if (this.history.position < this.history.stack.length - 1) {
                this.history.stack = this.history.stack.slice(0, this.history.position + 1);
            }

            this.history.stack.push(state);

            // 维护历史记录大小
            if (this.history.stack.length > this.history.maxSteps) {
                this.history.stack.shift();
            } else {
                this.history.position++;
            }

            this.editor.emit('history:changed', {
                canUndo: this.canUndo(),
                canRedo: this.canRedo()
            });
        }, this.debounceDelay);
    }

    /**
     * 还原状态
     */
    _restoreState() {
        if (!this.canvas) return;

        const state = this.history.stack[this.history.position];
        this.canvas.loadFromJSON(state, () => {
            this.canvas.renderAll();
            this.editor.emit('history:restored', this.history.position);
        });
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 监听对象修改事件
        this.canvas.on('object:modified', () => {
            this._recordState();
        });

        // 监听对象添加事件
        this.canvas.on('object:added', () => {
            this._recordState();
        });

        // 监听对象删除事件
        this.canvas.on('object:removed', () => {
            this._recordState();
        });

        // 监听画布清空事件
        this.canvas.on('canvas:cleared', () => {
            this._recordState();
        });
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            // 清除延迟记录定时器
            if (this.debounceTimeout) {
                clearTimeout(this.debounceTimeout);
            }

            this.history = {
                stack: [],
                position: -1,
                maxSteps: this.history.maxSteps
            };
        }
        super.destroy();
    }
} 